package com.kevin.Code.String;

/**
 * @author Vinlee Xiao
 * @Classname WildcardMatching
 * @Description Leetcode 44 同配符匹配 难度 困难 类似Leetcode 10
 * @Date 2021/11/12 20:01
 * @Version 1.0
 */
public class WildcardMatching {
    /**
     * 自己思路1
     * 动态规划
     *
     * @param s
     * @param p
     * @return
     */
    public boolean isMatch(String s, String p) {

        int len1 = s.length();
        int len2 = p.length();

        //表示s中第i个字符串和p中第几个字符串匹配
        boolean[][] dp = new boolean[len1 + 1][len2 + 1];

        //base line
        dp[0][0] = true;
        for (int i = 0; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {

                //分两种情况
                if (p.charAt(j - 1) == '*') {
                    //*匹配空字符串 就相当于不匹配
                    dp[i][j] = dp[i][j - 1];
                    //匹配1个或2 个多个
                    //匹配空字符串 匹配多个
                    if (i > 0) {
                        dp[i][j] = dp[i][j] || dp[i - 1][j];
                    }

                } else {
                    if (matchStr(s, p, i, j)) {
                        dp[i][j] = dp[i - 1][j - 1];
                    }
                }
            }
        }

        return dp[len1][len2];
    }

    /**
     * @param s
     * @param p
     * @param i
     * @param j
     * @return
     */
    private static boolean matchStr(String s, String p, int i, int j) {

        if (i == 0) {
            return false;
        }
        if (p.charAt(j - 1) == '?') {
            return true;
        }
        return s.charAt(i - 1) == p.charAt(j - 1);
    }

    /**
     * @param s
     * @param p
     * @return
     */
    public boolean isMatch1(String s, String p) {

        int len1 = s.length();
        int len2 = p.length();

        //表示s中第i个字符串和p中第几个字符串匹配
        boolean[][] dp = new boolean[len1 + 1][len2 + 1];

        for (int i = 0; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {

                if (p.charAt(j - 1) == '*') {
                    //*匹配空字符串 就相当于不匹配
                    dp[i][j] = dp[i][j - 1];
                    //匹配1个或2 个多个
                    //匹配空字符串 匹配多个
                    if (i > 0) {
                        dp[i][j] = dp[i][j] || dp[i - 1][j];
                    }

                } else if (i > 0 && (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1))) {

                    dp[i][j] = dp[i - 1][j - 1];

                }

            }

        }

        return dp[len1][len2];
    }


    public static void main(String[] args) {
        WildcardMatching wildcardMatching = new WildcardMatching();
        boolean match = wildcardMatching.isMatch("aa", "a");
        System.out.println(match);
    }
}
